import router from 'umi/router';
import { message } from 'antd';
import {
  checkInsTemplateData,
  checkAccuTemplateData,
  getInsDiffData,
  getAccuDiffData,
  getInsDiffDataDet,
  getAccuDiffDataDet,
  insCancelGoBack,
  accuCancelGoBack,
  insOkGoBack,
  accuOkGoBack,
  getInsLsPkgName,
  getAccuLsPkgName,
  getjoinIdeList,
  insAmoRecalculation,
  accuAmoRecalculation,
  getInsExecAffirm,
  getAccuExecAffirm,
  execImportData,
  insImport,
  accuImport,
  updateInsDiffAmo,
  updateAccuDiffAmo,
} from '@/services/socialbill';
import * as service from '@/services/socket';

export default {
  state: {
    fileId: '',
    fileName: '',
    batchQuery: {},
    formFieldsValue: {},
    expandForm: false,
    DifferenceData: {
      // 列表数据
      dealCount: 0,
      unDealCount: 0,
      diffAmoCount: 0,
      importDiffCount: 0,
      pageDto: {
        list: [],
        pagination: {
          current: 1,
          pageSize: 10,
          total: 10,
        },
      },
    },
    assCodeArr: ['old', 'workOut', 'injuries', 'health', 'birth'],
    diffModalData: {
      diffVisible: false,

      handleSource: [],
      detailSource: [],
      hshdRegFlag: 1,
      pkgData: [],
      joinIdeList: [],
      diffState: 1,
      payWage: 0,
      insGrpId: '',
      accuGrpId: '',
      insDifferentDataId: '',
      accuDifferentDataId: '',
      isCreateFee: '',
      isUpdateDiffAmount: '',
      sumDiffAmt: '',
    },
    nowPage: 1,
    pageNum: 10,
    resultInfo: {
      // 结果数据必传
      batchName: '', // 任务名称
      taskCount: 0, // 导入数据
      successCount: 0, // 成功数据
      errorCount: 0, // 失败数据
      batchNo: '', // 批次号
      errorUrl: '',
      errorParams: null, // 下载错误数据参数
      isErrorData: 2, // 1是有错误数据，2没有错误数据
      isDiffData: 2, // 1有差异，2没有差异
    },
    isBackShow: false, // 是否回盘的modal的显隐
    isError: false, // 是否有错误信息
    currentStep: 0,
    diffAmoVisible: false,
    //  showProgress: false,
  },
  effects: {
    *execImportData({ payload }, { call }) {
      const res = yield call(execImportData, payload);
      return res;
    },
    *checkTemplate({ payload }, { call, put, select }) {
      const assType = yield select(state => state.handlediff.batchQuery.assType);
      const response = yield call(
        Number(assType) === 1 ? checkInsTemplateData : checkAccuTemplateData,
        payload
      );
      if (response.success) {
        yield put({
          type: 'getTemplateData',
          payload: response.data,
        });
      } else {
        message.warning(`${response.message || '未配置回盘模版'}`);
      }
    },

    *fetchDiffData({ payload }, { call, put, select }) {
      const {
        pageArg: { currentPage, pageSize },
      } = payload;
      const billId = yield select(state => state.handlediff.batchQuery.billId);
      const assType = yield select(state => state.handlediff.batchQuery.assType);
      const response = yield call(Number(assType) === 1 ? getInsDiffData : getAccuDiffData, {
        billId,
        ...payload,
      });
      if (response.success) {
        yield put({
          type: 'getDiffDataDetial',
          payload: {
            data: response.data,
            currentPage,
            pageSize,
          },
        });
      } else {
        message.warning(`${response.message || '查询失败'}`);
      }
    },
    *fetchDiffDataDet({ payload }, { call, put, select }) {
      const assType = yield select(state => state.handlediff.batchQuery.assType);
      const response = yield call(
        Number(assType) === 1 ? getInsDiffDataDet : getAccuDiffDataDet,
        payload
      );
      // 先清空表格数据
      yield put({
        type: 'updateDiffModalData',
        payload: {
          detailSource: [],
        },
      });
      if (response.success) {
        yield put({
          type: 'getDiffDataDet',
          payload: response.data,
        });
      } else {
        message.warning(`${response.message || '查询失败'}`);
      }
    },
    *execCancelGoBack({ payload }, { call, select }) {
      const assType = yield select(state => state.handlediff.batchQuery.assType);
      const response = yield call(
        Number(assType) === 1 ? insCancelGoBack : accuCancelGoBack,
        payload
      );
      if (response.success) {
        router.goBack();
      } else {
        message.warning(`${response.message || '操作失败'}`);
      }
    },
    *execGoBack({ payload }, { call, select }) {
      const assType = yield select(state => state.handlediff.batchQuery.assType);
      const response = yield call(Number(assType) === 1 ? insOkGoBack : accuOkGoBack, payload);

      if (response.success) {
        router.goBack();
      } else {
        message.warning(`${response.message || '操作失败'}`);
      }
    },
    *fetchLsPkgName({ payload }, { call, put, select }) {
      const assType = yield select(state => state.handlediff.batchQuery.assType);

      const response = yield call(
        Number(assType) === 1 ? getInsLsPkgName : getAccuLsPkgName,
        payload
      );

      if (response.success) {
        yield put({
          type: 'updateDiffModalData',
          payload: { pkgData: response.data },
        });
      } else {
        message.warn(`${response.message || '查询失败'}`);
      }
    },
    *fetchJoinIdeList({ payload }, { call, put }) {
      const response = yield call(getjoinIdeList, payload);
      if (response.success) {
        yield put({
          type: 'updateDiffModalData',
          payload: { joinIdeList: response.data },
        });
      } else {
        message.warning(`${response.message || '查询失败'}`);
      }
    },
    *handlediff({ payload, callback }, { call, put, select }) {
      const assType = yield select(state => state.handlediff.batchQuery.assType);

      const response = yield call(
        Number(assType) === 1 ? insAmoRecalculation : accuAmoRecalculation,
        payload
      );
      if (response.success) {
        yield put({
          type: 'getDiffDataDet',
          payload: response.data,
        });
        callback(response.success);
      } else {
        message.warning(`${response.message || '操作失败'}`);
      }
    },
    *execAffirm({ payload }, { call, select, put }) {
      const assType = yield select(state => state.handlediff.batchQuery.assType);
      const currentStep = yield select(state => state.handlediff.currentStep);
      const response = yield call(
        Number(assType) === 1 ? getInsExecAffirm : getAccuExecAffirm,
        payload
      );
      if (response.success) {
        if (payload.confirmImport === 1) {
          yield put({
            type: 'updateModelData',
            payload: {
              currentStep: currentStep + 2,
              isBackShow: false,
            },
          });
        } else {
          yield put({
            type: 'updateModelData',
            payload: {
              isBackShow: false,
            },
          });
        }
      } else {
        message.warning(`${response.message || '操作失败'}`);
      }
    },
    // 上传文件:批量进度
    uploadFileWithProgress:[
      function* ({ payload }, { call, put, select }) {
      // /osApi/insBillApi/insImport
      const assType = yield select(state => state.handlediff.batchQuery.assType);
      const response = yield call(Number(assType) === 1 ? insImport : accuImport, payload);

      if (response.success) {
        yield put({
          type: 'updateModelData',
          payload: { batchId: response.data.batchId },
        });
        if (response.data && response.data.successProp !== 100) {
          yield call(service.socketChannel, {
            type: 'sub',
            data: {
              to: response.data && (response.data.batchId || response.data),
              type: Number(assType) === 1 ? 'osInsBill' : 'osAccuBill',
            },
          });
        } else {
          yield put({
            type: 'updateFileTask',
            payload: response.data,
          });
        }
      } else {
        // 上传失败
        message.warning(`${response.message || '上传失败'}`);
      }
      return response;
    },
    {type:'throttle',ms:10000}
  ],
    *updateDiffAmo({ payload }, { select, call }) {
      const billId = yield select(state => state.handlediff.batchQuery.billId);
      const assType = yield select(state => state.handlediff.batchQuery.assType);
      const response = yield call(Number(assType) === 1 ? updateInsDiffAmo : updateAccuDiffAmo, {
        billId,
        ...payload,
      });
      if (response.success) {
        message.success('操作成功！');
        return response;
      }
      return message.warning(`${response.message || '查询失败'}`);
    },

    // 更新批量任务数据
    *updateFileTask({ payload }, { select, put }) {
      let resultInfo = yield select(state => state.handlediff.resultInfo);
      const assType = yield select(state => state.handlediff.assType);
      const cacheKey = yield select(state => state.handlediff.cacheKey);

      let currentStep = 0;
      let showProgress = true;
      // let isBackShow = false;
      let isError = false;
      if (payload.successProp === 100) {
        showProgress = false;

        // // 都端保证永远有isErrorData 故注释掉
        // // if (payload.isErrorData === undefined) {
        // //   currentStep = 2;
        // // } else
        // if (Number(payload.isErrorData) === 2) {
        //   // 没有错误数据
        //   // 有差异数据和无差异数据统一处理
        //   currentStep += 1;
        //   yield put({
        //     type: 'fetchDiffData',
        //     payload: {
        //       pageArg: {
        //         currentPage: 1,
        //         pageSize: 10,
        //       },
        //     },
        //   });
        //   // if (Number(payload.isDiffData) === 1) {

        //   // } else {
        //   //   // isBackShow = true;
        //   //   // currentStep += 1;
        //   // }
        // } else {
        //   isError = true;
        // }

        // 字典1是2否
        if (Number(payload.isErrorData) === 1) {
          isError = true;
        }
        // 没有错误数据
        else if (Number(payload.isErrorData) === 2) {
          // 有差异数据
          if (Number(payload.isDiffData === 1)) {
            currentStep = 1;
            yield put({
              type: 'fetchDiffData',
              payload: {
                pageArg: {
                  currentPage: 1,
                  pageSize: 10,
                },
              },
            });
          }
          // 没有差异数据
          else if (payload.isDiffData === 2) {
            // 没有差异
            currentStep = 2;
          }
        }
        resultInfo.errorParams = {
          batNo: payload.batNo,
          cacheKey,
        };
        resultInfo = {
          ...resultInfo,
          ...payload,
          errorUrl:
            Number(assType) === 1
              ? '/osApi/insBillApi/exportExcelErrData'
              : '/osApi/accuBillApi/exportExcelErrData',
        };
      }

      yield put({
        type: 'updateModelData',
        payload: {
          resultInfo,
          showProgress,
          progressPercent: payload.successProp,
          currentStep,
          // isBackShow,
          isError,
        },
      });
    },
  },
  reducers: {
    // 设置页签状态
    updateModelData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    // 获取模版的入参
    getTemplateData(state, { payload }) {
      const fileId = payload.split('|')[0];
      const fileName = payload.split('|')[1];
      return {
        ...state,
        fileId,
        fileName,
      };
    },
    // 更新state数据
    updateDifferenceData(state, { payload }) {
      return {
        ...state,
        DifferenceData: {
          // 列表数据
          ...state.DifferenceData,
          pageDto: {
            ...state.DifferenceData.pageDto,
            pagination: {
              ...state.DifferenceData.pageDto.pagination,
              current: payload.current,
              pageSize: payload.pageSize,
            },
          },
        },
      };
    },

    getDiffDataDetial(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      return {
        ...state,
        DifferenceData: {
          ...data,
          pageDto: {
            list: data.pageDto.pageRecords,
            pagination: {
              current: currentPage,
              pageSize,
              total: data.pageDto.totalCount,
            },
          },
        },
      };
    },
    getDiffDataDet(state, { payload }) {
      const { actlDto, detDto, ordDto } = payload;
      const assCodeArr =
        Number(state.batchQuery.assType) === 1
          ? ['old', 'workOut', 'injuries', 'health', 'birth']
          : ['accu'];
      const actlDtoson = {};
      const ordDtoson = {};
      Object.keys(actlDto).forEach(key => {
        if (assCodeArr.indexOf(key) > -1) {
          Object.keys(payload.actlDto[key]).forEach(keys => {
            actlDtoson[`${key}_${keys}`] = payload.actlDto[key][keys];
          });
        }
      });
      Object.keys(ordDto).forEach(key => {
        if (assCodeArr.indexOf(key) > -1) {
          Object.keys(payload.ordDto[key]).forEach(keys => {
            ordDtoson[`${key}_${keys}`] = payload.ordDto[key][keys];
          });
        }
      });
      return {
        ...state,
        diffModalData: {
          ...state.diffModalData,
          handleSource: [
            { ...payload.ordDto, billTypeName: '申报数据', ...ordDtoson },
            { ...payload.actlDto, billTypeName: '回盘数据', ...actlDtoson },
          ],
          detailSource: payload.detDto.listDto,
          sumDiffAmt: detDto.sumDiffAmt,
          ...payload,
        },
      };
    },
    getInsPkg(state, { payload }) {
      return {
        ...state,
        diffModalData: {
          ...state.diffModalData,
          pkgData: payload,
        },
      };
    },
    updateDiffModalData(state, { payload }) {
      return {
        ...state,
        diffModalData: {
          ...state.diffModalData,
          ...payload,
        },
      };
    },
  },
  subscriptions: {
    socket({ dispatch }) {
      return service.listen(action => {
        switch (action.type) {
          case 'osInsBill':
            dispatch({
              type: 'updateFileTask',
              payload: action.data,
            });
            // 全局保存
            dispatch({
              type: 'publicdata/updateBatchTaskData',
              payload: action.data,
            });
            break;
          case 'osAccuBill':
            dispatch({
              type: 'updateFileTask',
              payload: action.data,
            });
            // 全局保存
            dispatch({
              type: 'publicdata/updateBatchTaskData',
              payload: action.data,
            });
            break;
          default:
        }
      });
    },
  },
};
